package com.nuosu;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.googlecode.tesseract.android.TessBaseAPI;

import java.io.File;

public class MainActivity extends Activity {
    TextView txtView;
    private boolean ocrAble = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initTessBaseData();
        typeface = Typeface.createFromAsset(getAssets(), "fonts/FZYWBT.ttf");
        txtView = (TextView) findViewById(R.id.textView);
        txtView.setTypeface(typeface);
    }

    Typeface typeface;
    private TessBaseAPI mTess;

    private void initTessBaseData() {
        mTess = new TessBaseAPI();
        String datapath = Environment.getExternalStorageDirectory() + File.separator + "nuosu";
        String language = "nuosu";
        File dir = new File(datapath);
        if (!dir.exists()) dir.mkdirs();
        mTess.init(datapath, language);
    }

    public void onClick(View v) {
        if (!ocrAble) return;
        ocrAble = false;
        new Thread() {
            @Override
            public void run() {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.nuosu03);
                mTess.setImage(bitmap);
                String result = mTess.getUTF8Text();
                handler.sendMessage(handler.obtainMessage(0, result));
            }
        }.start();
    }

    public void onCreatClick(View view) {
        CreatImage.creatImages(this);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            txtView.setText((String) msg.obj);
            Toast.makeText(MainActivity.this, "识别完成", Toast.LENGTH_SHORT).show();
            ocrAble = true;
        }
    };
}
